package com.fdm.controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fdm.model.Book;
import com.fdm.model.dao.BookDAO;
import com.fdm.util.exceptions.UniqueConstraintException;

@Controller
public class BookController {
	@Autowired
	private BookDAO bookDAO;
	
	@RequestMapping(value="/admin/addBookToInventory.do", method=RequestMethod.POST)
	public @ResponseBody String addNewBookToInventory(Model model, HttpServletRequest request) throws IOException{
		String returnText="";
		String title=request.getParameter("title");
		String author=request.getParameter("author");
		String isbn=request.getParameter("isbn");
		int totalCopies=Integer.parseInt(request.getParameter("bookCount"));
		Book book=new Book(title, author, isbn, totalCopies);
		try{
			bookDAO.newBook(book);
			returnText= "The book has been added to FDM's inventory";
		}
		catch(UniqueConstraintException uce){
			returnText= "The book <b>"+book.getTitle()+"</b> has not been added to FDM's inventory";
		}
		return returnText;
	}
}
